<?php

namespace app\admin\controller;

use think\Request;
use think\facade\Db;
use think\facade\Session;
use app\common\model\Admin;
use app\common\model\AuthRule;
use app\common\model\AuthGroup;

class AdminController extends BaseController
{

    public function adminInfo(Request $request)
    {
        $admin_info = $request->admin_info;
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(!empty($data['password']))
            {
                $data['password'] = md5($data['password'].$admin_info['salt']);
            }else{
                unset($data['password']);
            }
            $data['update_time'] = time();

            Admin::update($data, ['id'=>$admin_info['id']]);
            //重新获取session
            $admin_info = Admin::getAdminInfo(['a.id'=>$admin_info['id']]);
            Session::delete('admin_info');
            unset($admin_info['salt']);
            unset($admin_info['password']);
            Session::set('admin_info',$admin_info);

            return returnSuccess('修改成功');
        }else{
            $data['admin_info'] = $admin_info;

            return view('admin/admin_info', $data);
        }
    }


    /**
     * 权限菜单
     * @params string
     * @return
     */
    public function authRule()
    {
        if($this->method == 'POST')
        {
            $menu = AuthRule::order(['weigh'=>'asc', 'id'=>'asc'])->select();
            return json($menu);
        }else{
            return view('admin/auth_menu/auth_rule');
        }
    }

    /**
     * 修改权限菜单栏目状态
     * @params string
     * @return
     */
    public function editAuthRuleState(Request $request)
    {
        if($this->method == 'POST')
        {
            $id = $request->post('id');
            $state = $request->post('state');

            $res = Db::name('auth_rule')->where('id', $id)->update(['status'=>$state]);

            return returnSuccess('修改成功');
        }else{
            return returnFail('请求方式错误');
        }
    }

    /**
     * 添加栏目
     * @params string
     * @return
     */
    public function addAuthRule(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['title']) || empty($data['route']))
            {
                return returnFail('缺少必填项');
            }
            if($data['type'] == 1 && AuthRule::getPid($data['pid']) != 0)
            {
                return returnFail('目前菜单只支持到2级!');
            }
            if(Db::name('auth_rule')->where('route', $data['route'])->find())
            {
                return returnFail($data['route'].'路由规则已存在!');
            }
            AuthRule::create($data);
            return returnSuccess('添加成功');
        }else{
            $pid = $request->get('pid',0);
            //获取树形栏目目前只支持2级栏目
            $tree_menu = AuthRule::treeMenu();
            $assign['pid'] = $pid;
            $assign['tree_menu'] = $tree_menu;

            return view('admin/auth_menu/add_auth_rule', $assign);
        }
    }

    /**
     * 修改栏目
     * @params string
     * @return
     */
    public function editAuthRule(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['title']) || empty($data['route']))
            {
                return returnFail('缺少必填项');
            }
            AuthRule::update($data, ['id'=>$data['id']]);
            return returnSuccess('修改成功');
        }else{
            $info = AuthRule::find($request->get('id'));
            //获取树形栏目目前只支持2级栏目
            $tree_menu = AuthRule::treeMenu();

            $assign['info'] = $info;
            $assign['tree_menu'] = $tree_menu;

            return view('admin/auth_menu/edit_auth_rule', $assign);
        }
    }

    /**
     * 删除栏目
     * @params string
     * @return
     */
    public function delAuthRule(Request $request)
    {
        $id = $request->post('id');
        //查找自己下面的子栏目/权限
        $ch = AuthRule::where('pid', $id)->column('id');
        if(!empty($ch))
        {
            $id = array_merge($ch, [$id]);
        }
        $res = AuthRule::whereIn('id', $id)->delete();
        if($res)
        {
            return returnSuccess('删除成功');
        }
        return returnFail('删除失败');
    }

    /**
     * 角色管理
     * @params string
     * @return
     */
    public function authGroup()
    {
        if($this->method == 'POST')
        {
            $query = new AuthGroup();
            $total = $query->count('id');
            $list  = $query->order('id','asc')->page($this->page, $this->limit)->select()->toArray();

            return returnData($list, $total);
        }else{
            return view('admin/auth_group/auth_group_list');
        }
    }

    /**
     * 添加角色
     * @params string
     * @return
     */
    public function addAuthGroup(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['name']))
            {
                return returnFail('请填入角色名称');
            }
            if(!isset($data['rules']) || empty($data['rules']))
            {
                return returnFail('请选择栏目权限');
            }
            if(AuthGroup::where('name',$data['name'])->find())
            {
                return returnFail('角色名称已存在');
            }
            $data['rules'] = implode(',', $data['rules']);

            $res = AuthGroup::create($data);
            if($res)
            {
                return returnSuccess('添加成功');
            }
            return returnFail('添加成功');
        }else{
            $tree_menu = AuthRule::fullTreeMenu();
            $assign['tree_menu'] = $tree_menu;

            return view('admin/auth_group/add_auth_group', $assign);
        }
    }

    /**
     * 编辑角色
     * @params string
     * @return
     */
    public function editAuthGroup(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['name']))
            {
                return returnFail('请填入角色名称');
            }
            if(!isset($data['rules']) || empty($data['rules']))
            {
                return returnFail('请选择栏目权限');
            }
            $data['rules'] = implode(',', $data['rules']);

            $res = AuthGroup::update($data, ['id'=>$data['id']]);
            if($res)
            {
                return returnSuccess('修改成功');
            }
            return returnFail('修改成功');
        }else{
            $tree_menu = AuthRule::fullTreeMenu();
            $assign['tree_menu'] = $tree_menu;
            $assign['info'] = AuthGroup::find($request->get('id'));

            return view('admin/auth_group/edit_auth_group', $assign);
        }
    }

    /**
     * 删除角色
     * @params string
     * @return
     */
    public function delAuthGroup(Request $request)
    {
        if($this->method == 'POST')
        {
            $id = $request->post('id');
            Db::name('auth_group')->where('id', $id)->delete();

            return returnSuccess('删除成功');
        }
        return returnFail('非法请求');
    }

    /**
     * 后台管理员列表
     * @params string
     * @return
     */
    public function adminList(Request $request)
    {
        if($this->method == 'POST')
        {
            $admin_info = $request->admin_info;
            $where = [];
            if($admin_info['rules'] != '*')
            {
                $where['group_id'] = $admin_info['group_id'];
            }
            $query = Admin::alias('a')->where($where)->join('auth_group g','a.group_id = g.id')->field('a.*,g.name as rule_name');
            $total = $query->count('a.id');
            $list  = $query->order('a.id','asc')->page($this->page, $this->limit)->select()->toArray();

            return returnData($list, $total);
        }else{
            return view('admin/admin/admin_list');
        }
    }

    /**
     * 编辑后台管理员
     * @params string
     * @return
     */
    public function editAdmin(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['username']))
            {
                return returnFail('请填入账号名称');
            }
            if(Admin::where('username',$data['username'])->where('id','<>', $data['id'])->find())
            {
                return returnFail('账号名称已存在');
            }

            if(Admin::where('phone',$data['phone'])->where('id','<>', $data['id'])->find())
            {
                return returnFail('手机号已存在');
            }

            if(!empty($data['password']))
            {
                $data['password'] = md5($data['password'].$data['salt']);
            }else{
                unset($data['password']);
            }

            $res = Admin::update($data, ['id'=>$data['id']]);
            if($res)
            {
                return returnSuccess('修改成功');
            }
            return returnFail('修改失败');
        }else{
            $assign['auth_group'] = AuthGroup::getAuthGroup($request->admin_info);
            $assign['admin_info'] = Admin::find($request->get('id'));

            return view('admin/admin/edit_admin', $assign);
        }
    }

    /**
     * 添加后台管理员
     * @params string
     * @return
     */
    public function addAdmin(Request $request)
    {
        if($this->method == 'POST')
        {
            $data = $request->post();
            if(empty($data['username']))
            {
                return returnFail('请填入账号名称');
            }
            if(Admin::where('username',$data['username'])->find())
            {
                return returnFail('账号名称已存在');
            }
            if(Admin::where('phone',$data['phone'])->find())
            {
                return returnFail('手机号已存在');
            }
            $data['salt'] = get_random_str(6);
            $data['password'] = md5($data['password'].$data['salt']);

            $res = Admin::create($data);
            if($res)
            {
                return returnSuccess('添加成功');
            }
            return returnFail('添加失败');
        }else{
            $assign['auth_group'] = AuthGroup::getAuthGroup($request->admin_info);

            return view('admin/admin/add_admin', $assign);
        }
    }

    /**
     * 删除后台管理员
     * @params string
     * @return
     */
    public function delAdmin(Request $request)
    {
        if($this->method == 'POST')
        {
            $id = $request->post('id');
            Db::name('admin')->where('id', $id)->delete();

            return returnSuccess('删除成功');
        }
        return returnFail('非法请求');
    }
}
